<template>
	<block>
		<hxt-layout id="hxt-layout" title="账单" svc="bill" initTitle="账单加载失败" @initPage="initPage">
			<view class="hxt-flex-column" style="background-color: #fff;">
				<!-- <van-dropdown-menu active-color="#1989fa">
					<van-dropdown-item :value="idx" :options="urlList" @change="change"></van-dropdown-item>
				</van-dropdown-menu> -->
				<van-notice-bar color="#1989fa" background="#ecf9ff" left-icon="info-o" v-if="query.rowCount">
				账单共计{{query.rowCount}}条，总销售额：{{query.Sum}}元（其中现金：{{query.XJ}}元，微信：{{query.WX}}元，支付宝：{{query.ZFB}}元），总销售数量：{{query.Count}}，总利润：{{query.Profit}}元
				</van-notice-bar>
				<view class="hxt-flex-fill" style="overflow: hidden;">
					<hxt-scroll ref="scrollEL" id="scrollEL" scroll-y style="height:100%;" scroll-with-animation="true"
						enable-back-to-top="true" :enhanced="true" :bounces="false" @loadData="loadData">
						<view v-for="(item,index) in list" :key="index" style="margin: 20rpx;">
							<van-card :tag="item.payType==0?'现金':item.payType==1?'微信':item.payType==2?'支付宝':''" :origin-price="item.eoOldProce" :price="item.biPrice"
								:num="item.biCount">
								<view slot="thumb" @click="AddCar(3,item.biId)">
									<van-image width="88px" height="111px" fit="aspectFit"
										src="https://img01.yzcdn.cn/vant/ipad.jpeg"></van-image>
								</view>
								<view slot="title" style="font-size: 30rpx;font-weight: 700;">
									{{item.eoBrand}}
								</view>
								<view slot="desc">
									型号：{{item.eoModel}}

								</view>
								<view slot="tags">
									售出时间：{{item.time}}

								</view>
								<view slot="price-top">
									适用车型：{{item.eoApplications}}
									<!-- 时间：{{item.eoTime}} -->
								</view>
								<view slot="bottom" :class="item.biProfit<0?'text-red':'text-green'">
									总利润：{{item.biProfit}}
								</view>
								<view slot="footer" class="hxt-flex">
									<view class="hxt-flex-fill text-left">
										{{item.addTime}}
									</view>
									<view>
										<van-button :disabled="item.biStatus!=0||item.openId!=currentUser.openId" size="mini" @click="AddCar(1,item.biId)">退换
										</van-button>
										<van-button :disabled="!currentUser.root&&item.openId!=currentUser.openId" size="mini" @click="del(item.biId,index)">删除</van-button>
									</view>
								</view>
							</van-card>

						</view>
					</hxt-scroll>
				</view>
			</view>
			<movable-area style="position: absolute;top: 10%;right: 10%;width: 90%;height: 70%;pointer-events: none;">
				<movable-view :x="x" :y="y" class="hxt-maview" direction="all">
					<view class="cu-tag round bg-blue padding shadow-blur" @click="AddCar(0)">记账</view>
				</movable-view>
			</movable-area>
			<page-container v-if="showAdd" :show="showAdd" style="height: 100%;width: 100vm;" position="center"
				@clickoverlay="closeAdd" @afterleave="closeAdd">
				<view class="hxt-flex-column">
					<view class="hxt-flex-fill" style="height: 1px;">
						<scroll-view scroll-y style="height:100%;background-color: #F5F5F5;" enable-back-to-top="true"
							:enhanced="true" :bounces="false">
							<view v-if="form.optType==3">
								<van-cell-group title="机油信息">
									<van-cell title="机油品牌" :value="form.eoBrand"></van-cell>
									<van-cell title="机油型号" :value="form.eoModel"></van-cell>
									<van-cell title="适用车型" :value="form.eoApplications"></van-cell>
									<van-cell title="容量">
										<view>
											{{form.eoCapacity}}L
										</view>
									</van-cell>
									<van-cell title="机油批价">
										<view>
											￥{{form.eoOldProce}}
										</view>
									</van-cell>
									<van-cell title="机油推荐售价">
										<view>
											￥{{form.eoPrice}}
										</view>
									</van-cell>
								</van-cell-group>
								<van-cell-group title="账单信息">
									<van-cell title="机油实际售价">
										<view>
											￥{{form.biPrice}}
										</view>
									</van-cell>
									<van-cell title="销售数量" :value="form.biCount"></van-cell>
									<van-cell title="销售总额">
										<view>
											￥{{form.biSum}}
										</view>
									</van-cell>
									<van-cell title="采购总额">
										<view>
											￥{{form.bioldSum}}
										</view>
									</van-cell>
									<van-cell title="总利润">
										<view>
											<van-tag :type="form.biProfit>0?'success':'danger'">￥{{form.biProfit}}
											</van-tag>
										</view>
									</van-cell>
									<van-cell title="销售时间" :value="form.time"></van-cell>
									<van-cell title="支付方式">
										<van-tag color="#ffe1e1" text-color="#ad0000">{{form.payType==0?'现金支付':form.payType==1?'微信支付':form.payType==2?'支付宝支付':''}}
										</van-tag>
									</van-cell>
									<van-cell title="入库时间" :value="form.addTime"></van-cell>
									<van-cell title="备注" title-width="40px" :value="form.biMark"></van-cell>
								</van-cell-group>
								<van-cell-group title="操作员信息">
									<van-cell title="姓名" :value="form.uiName"></van-cell>
									<van-cell title="openid" title-width="80px" :value="form.openId"></van-cell>
									<van-cell title="session_key" :value="form.session_key"></van-cell>
									<van-cell title="账号" :value="form.account"></van-cell>
									<van-cell title="操作时间" :value="form.upTime"></van-cell>
								</van-cell-group>
							</view>
							<view style="padding: 1rpx 0;" v-else>
								<view
									style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text class="text-red">*</text>
										<text style="font-weight: bold;">机油</text>
										<text v-if="!!form.eoId">（原订单：{{form.eoBrand}}【{{form.eoModel}}】） </text>
									</view>
									<view class="hxt-flex">
										<uni-data-picker class="hxt-flex-fill" placeholder="请选择机油" popup-title="请选择机油"
											:localdata="eo.list" v-model="form.mId" @change="change">
										</uni-data-picker>
									</view>
									<view v-if="!!formERR.eoBrandERR"
										style="color:#ee0a24;font-size:24rpx;text-align: right;margin-top: 10rpx;">
										{{formERR.eoBrandERR}}
									</view>
								</view>
								<view style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text class="text-red">*</text>
										<text style="font-weight: bold;">售出时间</text>
										<!-- <text v-if="!!item.gkMark">（{{item.gkMark}}）</text> -->
									</view>

									<view class="hxt-flex">
										<view class="hxt-flex-fill"
											style="box-sizing: border-box;border-radius: 8rpx;border: 2rpx solid #e5e5e5;">
											<view class="hxt-flex"
												style="align-items: center;justify-content: space-between;border-radius: 8rpx;font-size: 28rpx;height: 64rpx;padding: 0 20rpx;"
												@click="openTime">
												<view
													:style="[{color: (!form.currentDay||form.optType>0?'#c8c9cc':'')}]">
													{{form.currentDay||'请选择时间'}}
												</view>
											</view>
										</view>
									</view>
									<view v-if="!!formERR.stimeERR"
										style="color:#ee0a24;font-size:24rpx;text-align: right;margin-top: 10rpx;">
										{{formERR.stimeERR}}
									</view>
								</view>
								<view
									style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text class="text-red">*</text>
										<text style="font-weight: bold;">售价</text>
										<text v-if="!!currentEo">（正常售价：￥{{currentEo.eoPrice}}）</text>
										<!-- <text v-if="!!item.gkMark">（{{item.gkMark}}）</text> -->
									</view>
									<view class="inputborder">
										<hxt-input :disabled="form.optType>0" type="digit" :border="false"
											v-model="form.biPrice" placeholder="请输入售价">
										</hxt-input>
									</view>
								</view>
								<view
									style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text class="text-red">*</text>
										<text style="font-weight: bold;">售出数量</text>
										<text
											v-if="!!currentEo">（{{currentEo.eoStock<=0?'库存不足，请及时补货':'库存：'+currentEo.eoStock}}）</text>
									</view>
									<van-stepper :disabled="form.optType>0" :value="form.count" integer
										@change="onstepperChange"></van-stepper>
									<!-- <view class="inputborder">
										
										<hxt-input type="number" :border="false" v-model="form.eoStock" placeholder="请输入库存数量">
										</hxt-input>
									</view> -->
								</view>
								<view style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text class="text-red">*</text>
										<text style="font-weight: bold;">支付方式</text>
									</view>
									<van-radio-group :disabled="form.optType>0" :value="form.payType" bind:change="onChange" direction="horizontal" @change="onPayTypeChange">
									  <van-radio :name="0">现金支付</van-radio>
									  <van-radio :name="1">微信支付</van-radio>
									  <van-radio :name="2">支付宝支付</van-radio>
									</van-radio-group>
								</view>
								<view
									style="background-color: #FFFFFF;padding: 30rpx;margin: 20rpx;border-radius: 15rpx;">
									<view class="padding-bottom">
										<text style="font-weight: bold;">备注</text>
										<!-- <text v-if="!!item.gkMark">（{{item.gkMark}}）</text> -->
									</view>
									<view class="inputborder">
										<hxt-input class="hxt-flex-fill" :border="false" type="textarea" v-model="form.biMark" maxlength="400"
											placeholder="请输入备注" autosize show-word-limit>
										</hxt-input>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<view>
						<van-submit-bar :price="form.biPrice*form.count*100" button-text="提交订单" custom-class="submit-bar" :disabled="form.optType==3" @submit="submit" :safe-area-inset-bottom="false">
						</van-submit-bar>
						<!-- <button class="cu-btn round bg-cyan shadow" @click="submit"
							style="background-color: #1cbbb4;width: 100%;">保存</button> -->
					</view>
				</view>
			</page-container>
			<van-calendar :show="showTime" title="选择日期" :default-date="currentDay" :max-date="maxDate"
				:min-date="minDate" :show-confirm="false" @close="closeTime" @confirm="onConfirm" color="#07c160">
			</van-calendar>
		</hxt-layout>
		<hxt-loading id="hxt-loading"></hxt-loading>
	</block>
</template>
<script>
	import hxt from "@/utils/hxt.js"
	import uniDataSelect from "@/wxcomponents/uni/uni-data-select/components/uni-data-select/uni-data-select"
	import uniDataPicker from "@/wxcomponents/uni/uni-data-picker/components/uni-data-picker/uni-data-picker"
	export default {
		components: {
			uniDataSelect,
			uniDataPicker
		},
		data() {
			const app = getApp();
			var date = new Date();
			return {
				list: [],
				showAdd: false,
				oldform: null,
				currentEo: null,
				currentUser: app.globalData.currentUser,
				query: {
					eoApplications: '',
					mId: 0,
					beginTime: '',
					endTime: '',
					pageIndex: 1,
					pageSize: 20,
					Sum:0,
					Count:0,
					Profit:0,
					WX:'',
					XJ:'',
					ZFB:''
				},
				form: {
					optType: 0,
					mId: 0,
					payType:0,
					biPrice: '',
					count: 1,
					biMark: '',
					currentDay: '',
					openId: app.globalData.currentUser.openId,
					state:'bill'
				},
				minDate: new Date(date.getFullYear(), date.getMonth() - 2, date.getDate()).getTime(),
				maxDate: date.getTime(),
				formERR: {
					eoBrandERR: ''
				},
				showTime: false,
				eo: {
					list: [],
					load: false
				}
			}
		},
		onShow: function(e) {},
		methods: {
			initPage: function(e) { //初始化事件
				var _this = this;
				_this.form.currentDay = _this.formatDate(_this.form.currentDay);
				// const res = wx.getSystemInfoSync();
				// _this.form.oimodel = res.model;
				// _this.form.oibrand = res.brand;
				// _this.form.oiplatform = res.platform;
				_this.loadData();
			},
			loadData: function(e) {
				var _this = this;
				if (!e || e.refresh) {
					_this.query.pageIndex = 1;
				};
				hxt.post({
					url: hxt.domain + 'pc/enBillList',
					data: _this.query,
					ok: function(res) {
						if (res.data.code != 0) {
							hxt.Notify({
								type: 'danger',
								message: '加载失败：' + res.data.errmsg + '，请稍后重试！'
							});
							_this.$refs.scrollEL.refreshDone(_this.query.pageIndex != 1);
							_this.list = [];
							return;
						};
						var list = _this.query.pageIndex == 1 ? [] : _this.list;
						for (var i = 0; i < res.data.data.list.length; i++) {
							list.push(res.data.data.list[i]);
						};
						_this.list = list;
						_this.query.pageIndex = res.data.data.pageIndex + 1;
						_this.query.pageSize = res.data.data.pageSize;
						_this.query.rowCount = res.data.data.rowCount;
						_this.query.Sum = res.data.data.Sum;
						_this.query.Count = res.data.data.Count;
						_this.query.Profit = res.data.data.Profit;
						_this.query.XJ = res.data.data.XJ;
						_this.query.WX = res.data.data.WX;
						_this.query.ZFB = res.data.data.ZFB;
						_this.$refs.scrollEL.refreshDone(_this.query.pageIndex <= Math.ceil(res.data.data.rowCount / res.data.data.pageSize));
					},
					fail: function(res) {
						hxt.Notify({
							type: 'danger',
							message: '加载失败：' + res.errMsg + '，请稍后重试！'
						});
						_this.$refs.scrollEL.refreshDone(_this.query.pageIndex != 1);
						_this.list = [];
					}
				});
			},
			onPayTypeChange:function(e){
				this.form.payType=e.detail;
			},
			AddCar: function(type, biId) {
				var _this = this;
				hxt.post({
					url: hxt.domain + "pc/eoModelList",
					data: {},
					ok: function(res) {
						if (res.data.code != 0) {
							hxt.alert(res.data.errmsg, '获取机油列表失败');
							return;
						};
						_this.eo.list = res.data.data;
					},
					fail: function(res) {
						hxt.alert(res.errMsg, '获取机油列表失败');
					}
				});
				if(type>0){
					hxt.post({
						url: hxt.domain + "pc/enBillObj",
						data: {biId:biId},
						ok: function(res) {
							if (res.data.code != 0) {
								hxt.alert(res.data.errmsg, '获取账单详情失败');
								return;
							};
							var g=res.data.data;
							if (type == 3) {
								_this.form = g;
							};
							_this.form.biPrice = g.biPrice;
							_this.form.count = g.biCount;
							_this.form.biMark = g.biMark;
							_this.form.bioldMark = g.biMark;
							_this.form.currentDay = g.time;
							_this.form.eoBrand = g.eoBrand;
							_this.form.eoModel = g.eoModel;
							_this.form.eoId = g.eoId;
							_this.form.payType =g.payType;
							_this.form.biId = g.biId;
							_this.form.optType = type;
							_this.form.mId=String(g.eoMid),
							_this.oldform=JSON.stringify(_this.form);
							_this.showAdd = true;
						},
						fail: function(res) {
							hxt.alert(res.errMsg, '获取账单详情失败');
						}
					});
					return;
				};
				_this.form.optType = type;
				_this.showAdd = true;
			},
			change: function(e) {
				var _this = this;
				if (e.detail.value.length < 2) return;
				var bid = e.detail.value[0].value,
					mid = e.detail.value[1].value;
				var b = _this.eo.list.find(function(item) {
					return item.value == bid;
				});
				var m = b.children.find(function(item) {
					return item.value == mid;
				});
				if (m.eoBrand == _this.form.eoBrand && m.text == _this.form.eoModel) {
					_this.formERR.eoBrandERR = "品牌型号与原订单相同";
				} else {
					_this.formERR.eoBrandERR = "";
					if (_this.form.optType == 1) _this.form.biMark = _this.form.bioldMark + '  原订单：' + _this.form
						.eoBrand + '【' + _this.form.eoModel + '】更换为' + m.eoBrand + '【' + m.text + '】';
				};
				_this.currentEo = m;
			},
			onstepperChange: function(e) {
				this.form.count = e.detail;
			},
			openTime: function() { //开始/结束时间
				var _this = this;
				if (_this.form.optType > 0) return;
				_this.showTime = true;
			},
			formatDate(date) {
				if (!date) return '';
				date = new Date(date);
				return `${date.getFullYear()}-${(date.getMonth() + 1) < 10 ? '0' : ''}${date.getMonth() + 1}-${date.getDate() < 10 ? '0' : ''}${date.getDate()}`;
			},
			onConfirm: function(e) {
				var _this = this;
				_this.showTime = false;
				_this.form.currentDay = _this.formatDate(e.detail);
			},
			closeTime: function(e) {
				this.setData({
					showTime: false
				});
			},
			closeAdd: function(e) {
				var _this = this;
				_this.form.optType= 0;
				_this.form.mId= 0;
				_this.form.payType=0;
				_this.form.biPrice= '';
				_this.form.count= 1;
				_this.form.biMark= '';
				_this.form.currentDay= '';
				_this.form.openId= _this.currentUser.openId;
				_this.form.state='bill';
				_this.oldform = '';
				_this.showAdd = false;
			},
			submit: function(e) {
				var _this = this,form=_this.form;
				if (_this.oldform == JSON.stringify(_this.form)) return hxt.Notify({
					type: 'warning',
					message: '提交失败：信息未更改'
				});
				var form = _this.form;
				if (form.mId <= 0) return hxt.Notify({
					type: 'danger',
					message: '提交失败：请选择机油'
				});
				if (!!hxt.trim(_this.formERR.eoBrandERR)) return hxt.Notify({
					type: 'danger',
					message: '提交失败：' + _this.formERR.eoBrandERR
				});
				if (!hxt.trim(form.currentDay)) return hxt.Notify({
					type: 'danger',
					message: '提交失败：请选择时间'
				});
				if (!hxt.trim(form.biPrice)) return hxt.Notify({
					type: 'danger',
					message: '提交失败：请输入售价'
				});
				if (!hxt.trim(form.count)) return hxt.Notify({
					type: 'danger',
					message: '提交失败：请输入售出数量'
				});
				if (_this.currentEo.eoStock < form.count) return hxt.Notify({
					type: 'danger',
					message: '提交失败：售出数量不能大于库存数量'
				});
				form.openId=_this.currentUser.openId;
				hxt.confirm("确定提交订单？", "", function() {
					hxt.post({
						url: hxt.domain + "pc/eoBillAdd",
						data: form,
						ok: function(res) {
							if (res.data.code != 0) {
								hxt.Notify({type: 'danger',message: '操作失败：'+res.data.errmsg});
								return;
							};
							hxt.Notify({
								type: 'success',
								message: '操作成功',
								duration: 1000
							});
							_this.loadData();
							_this.closeAdd();
						},
						fail: function(res) {
							hxt.Notify({type: 'danger',message: '操作失败：'+res.errMsg});
						}
					});
				});
			},
			del: function(biId, idx) {
				var _this = this;
				hxt.confirm("注意：删除后不能找回", "确定删除吗?", function() {
					hxt.post({
						url: hxt.domain + "pc/eoBillAdd",
						data: {
							optType: 2,
							biId: biId,
							openId:_this.currentUser.openId,
							state:_this.form.state
						},
						ok: function(res) {
							if (res.data.code != 0) {
								hxt.Notify({
									type: 'danger',
									message: '删除失败：' + res.data.errmsg
								});
								return;
							};
							hxt.Notify({
								type: 'success',
								message: '删除成功',
								duration: 1000
							});
							_this.list.splice(idx, 1);
						},
						fail: function(res) {
							hxt.Notify({
								type: 'danger',
								message: '删除失败：' + res.errMsg
							});
						}
					});
				});
			},
		}
	}
</script>

<style>
	.inputborder {
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		background-color: #fff;
		padding: 1rpx 10rpx;
	}

	.van-cell {
		padding: 10rpx !important;
	}

	.txt-css {
		word-break: break-all;
		word-wrap: break-word;
		white-space: pre-line;
	}
	.submit-bar {
		position: sticky !important;
		z-index: 0 !important;
	}
</style>
